package org.wkg.lesson08;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 1.使用一个类来描述任务与任务时间
 * 2.组织任务和时间对应的对象
 * 3.提供一个方法可以提交任务
 * 4.要有一个线程任务
 */


public class MyTimer_2 {
    private BlockingQueue<MyTask1> queue = new PriorityBlockingQueue() {
    };

    public MyTimer_2() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    MyTask1 task = this.queue.take();
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= task.getTime()) {
                        // 时间到了，执行任务
                        task.getRunnable().run();
                    } else {
                        queue.put(task);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }


    public void schedule(Runnable runnable, long delay) throws InterruptedException {
        MyTask1 task = new MyTask1(runnable, delay);
        queue.put(task);
    }
}


class MyTask1 implements Comparable<MyTask1> {
    private Runnable runnable;
    private long time;

    public MyTask1(Runnable runnable, long delay) {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不能为空");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("任务时间不能为负数");
        }

        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask1 o) {
        if (this.getTime() > o.getTime()) {
            return 1;
        } else if (this.getTime() < o.getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}


